package com.tgjorgoski.utils;

import java.awt.Component;

import javax.swing.JPopupMenu;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class ViewUtils {
	public static void cleanUpPopupMenu(JPopupMenu popUpMenu) {
		//remove the starting separators 
		while (true) {
			if (popUpMenu.getComponent(0) instanceof JPopupMenu.Separator) {
				popUpMenu.remove(0);
			} else {
				break;
			}
		}
		//remove the ending separators and consecutive separators
		boolean separator=true;
		for(int i=popUpMenu.getComponentCount()-1; i>=0; i--) {
			Component comp = popUpMenu.getComponent(i);
			if (comp instanceof JPopupMenu.Separator) {
				if (separator) {
					popUpMenu.remove(i);
				} else {
					separator=true;
				}
			} else {
				separator=false;
			}
		}
	}
	
	private static boolean popupMenuVisible=false; 
	public static JPopupMenu createAndTrackPopupMenu() {
		JPopupMenu newPopup = new JPopupMenu();
		newPopup.addPopupMenuListener(new PopupMenuListener() {
			@Override
			public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
				popupMenuVisible=true;
			}
		
			@Override
			public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
				popupMenuVisible=false;
			}
		
			@Override
			public void popupMenuCanceled(PopupMenuEvent e) {
				popupMenuVisible=false;
			}
		});
		return newPopup;
	}
	public static boolean isPopupMenuVisible() {
		return popupMenuVisible;
	}
}
